package com.eascs.web.o2o.web.aging.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.view.ViewContext;
import com.eascs.tag.MenuTag;
import com.eascs.web.o2o.web.aging.entity.ProcessInfoEntity;
import com.eascs.web.o2o.web.aging.form.AgingQueryForm;
import com.eascs.web.o2o.web.aging.form.NodeAgingForm;
import com.eascs.web.o2o.web.aging.form.ProcessAgingForm;
import com.eascs.web.o2o.web.aging.service.IAgingService;
import com.eascs.web.o2o.web.aging.service.SysOrgService;
import com.eascs.web.o2o.web.aging.service.SysPermissionService;
import com.eascs.web.o2o.web.aging.service.TemplateService;
import com.eascs.web.o2o.web.common.BaseMasterViewController;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.wf.DicData;


@Controller
@RequestMapping("/aging")
public class AgingInfoListController extends BaseMasterViewController {

	@Autowired
	IAgingService AgingService;

	@Autowired
	SysPermissionService sysPermissionService;

	@Autowired
	TemplateService templateService;
	@Autowired
	SysOrgService sysOrgService;

	@RequestMapping("/index")
	public String index(AgingQueryForm entity) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "timeEffective");
		String agingUrl = "/raging/list";
		if (entity != null) {
			String billCode = entity.getBillCode() == null ? "" : entity.getBillCode();
			String debtStatus = entity.getDebtStatus() == null ? "" : entity.getDebtStatus();
			String ltdName = entity.getLtdName() == null ? "" : entity.getLtdName();
			String timeOutType = entity.getTimeOutType() == null ? "" : entity.getTimeOutType();
			String orgManager = entity.getOrgManager() == null ? "" : entity.getOrgManager();
			String provinceCode = entity.getProvinceCode() == null ? "" : entity.getProvinceCode();
			String createDateStart = entity.getCreateDateStart() == null ? "" : entity.getCreateDateStart();
			String createDateEnd = entity.getCreateDateEnd() == null ? "" : entity.getCreateDateEnd();
			agingUrl = UrlUtil.appendUrl(agingUrl, "billCode", billCode);
			agingUrl = UrlUtil.appendUrl(agingUrl, "debtStatus", debtStatus);
			agingUrl = UrlUtil.appendUrl(agingUrl, "ltdName", ltdName);
			agingUrl = UrlUtil.appendUrl(agingUrl, "timeOutType", timeOutType);
			agingUrl = UrlUtil.appendUrl(agingUrl, "orgManager", orgManager);
			agingUrl = UrlUtil.appendUrl(agingUrl, "provinceCode", provinceCode);
			agingUrl = UrlUtil.appendUrl(agingUrl, "createDateStart", createDateStart);
			agingUrl = UrlUtil.appendUrl(agingUrl, "createDateEnd", createDateEnd);
			agingUrl = agingUrl + "&agingIndex=";
		} else {
			agingUrl = agingUrl + "?agingIndex=";
		}

		List<ActOrgEntity> provinceList = sysOrgService.getOrgProvince();
		List<ProcessInfoEntity> procedures = AgingService.getProcess();
		ViewContext.put("vo", entity);
		ViewContext.put("agingUrl", agingUrl);
		ViewContext.put("procedures", procedures);
		ViewContext.put("provinceList", provinceList);
		return "aging/index";
	}

	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	public String showDetail(String billCode) {
		String detailUrl = "/raging/processDetail?billCode=" + billCode + "&processType=";
		List<ProcessInfoEntity> procedures = new ArrayList<ProcessInfoEntity>();
		String[] processCode = new String[] { "CREDIT", "INAUDIT", "BANK_REPORT", "DEPOSIT", "FINANCE_AUDIT" };
		String[] processName = new String[] { "征信调查", "内部审批", "面签提报", "保证金管理费", "财务审核" };
		for (int i = 0, len = processCode.length; i < len; i++) {
			ProcessInfoEntity pf = new ProcessInfoEntity();
			pf.setProcedureCode(processCode[i]);
			pf.setProcedureName(processName[i]);
			procedures.add(pf);
		}
		ViewContext.put("procedures", procedures);
		ViewContext.put("detailUrl", detailUrl);
		return "aging/agingInfoDetail";
	}

	@Override
	public void preHandle() {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "approvalManage");
	}

	/**
	 * 
	 * @Title: index
	 * @Description: 节点时效（结束流程）
	 * @author user
	 * @param entity
	 * @return
	 * @return String
	 * @throws @date
	 *             2017年9月21日 下午2:26:33
	 */
	
	@RequestMapping("/node_aging")
	public String nodeAgingFinished(HttpServletResponse httpServletResponse, HttpServletRequest request,NodeAgingForm entity) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "JDSXY");
		String agingUrl = "/raging/node_aging_list";
		if (StringUtils.isNotBlank(entity.getCatagory())) {
			List<DicData> dicList = templateService.getProcessTypeByCatagory(entity.getCatagory()).getModel();
			ViewContext.put("processTypeList", dicList);
			List<String> processTypeList = new ArrayList<String>();
			if (StringUtils.isNotBlank(entity.getProcessType())) {
				processTypeList.add(entity.getProcessType());
			} else {
				for (DicData dic : dicList) {
					processTypeList.add(dic.getCode());
				}
			}
			entity.setProcessTypeList(processTypeList);
		}
		if (StringUtils.isNotBlank(entity.getOper()) && StringUtils.equalsIgnoreCase(entity.getOper(), "download")) {
			OutputStream os = null;
			try {
				entity.setPageIndex(0);
				entity.setPageSize(10000);
				List<Object[]> list = AgingService.listNodeAgingInfoFinished(entity).getData();
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=node-time-finished.xls");
				httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
				saveNodeAging(list, httpServletResponse.getOutputStream());
			} catch (Exception e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
			return null;
		} else {
			String billCode = entity.getBillCode() == null ? "" : entity.getBillCode();
			String catagory = entity.getCatagory() == null ? "" : entity.getCatagory();
			String processType = entity.getProcessType() == null ? "" : entity.getProcessType();
			String nodesNa = entity.getNodesNa() == null ? "" : entity.getNodesNa();
			String nodeAuditors = entity.getNodeAuditors() == null ? "" : entity.getNodeAuditors();
			String NodeTimeS = entity.getNodeTimeS() == null ? "" : entity.getNodeTimeS();
			String NodeTimeE = entity.getNodeTimeE() == null ? "" : entity.getNodeTimeE();
			String dateStart = entity.getDateStart() == null ? "" : entity.getDateStart();
			String dateEnd = entity.getDateEnd() == null ? "" : entity.getDateEnd();
			String nodeStatus = entity.getNodeStatus() == null ? "" : entity.getNodeStatus();
			String dateStartb = entity.getDateStartb() == null ? "" : entity.getDateStartb();
			String dateEndb = entity.getDateEndb() == null ? "" : entity.getDateEndb();

			agingUrl = UrlUtil.appendUrl(agingUrl, "billCode", billCode);
			agingUrl = UrlUtil.appendUrl(agingUrl, "catagory", catagory);
			agingUrl = UrlUtil.appendUrl(agingUrl, "processType", processType);
			agingUrl = UrlUtil.appendUrl(agingUrl, "nodesNa", nodesNa);
			agingUrl = UrlUtil.appendUrl(agingUrl, "nodeAuditors", nodeAuditors);
			agingUrl = UrlUtil.appendUrl(agingUrl, "NodeTimeS", NodeTimeS);
			agingUrl = UrlUtil.appendUrl(agingUrl, "NodeTimeE", NodeTimeE);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateStart", dateStart);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateEnd", dateEnd);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateStartb", dateStartb);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateEndb", dateEndb);
			agingUrl = UrlUtil.appendUrl(agingUrl, "nodeStatus", nodeStatus);
			agingUrl = agingUrl + "&pageIndex=";
			
			// 流程大类
			List<DicData> catagoryList = sysPermissionService.getDicDataByType("processCatagory");
			ViewContext.put("catagoryList", catagoryList);
			// 流程类型
			List<DicData> list = templateService.getProcessTypeByCatagory(entity.getCatagory()).getModel();
			ViewContext.put("processTypeList", list);
			List<ProcessInfoEntity> procedures = AgingService.getProcess();
			ViewContext.put("vo", entity);
			ViewContext.put("nodeAgingUrl", agingUrl);
			ViewContext.put("procedures", procedures);
			ViewContext.put("rowNum", AgingService.listNodeAgingInfoFinished(entity).getDbRowCount());
			return "aging/nodeAgingList";
		}
	}

	/**
	 * 
	 * @Title: index
	 * @Description: 节点时效（未结束流程）
	 * @author user
	 * @param entity
	 * @return
	 * @return String
	 * @throws @date
	 */
	@RequestMapping("/node_aging2")
	public String nodeAgingUnfinished(HttpServletResponse httpServletResponse, HttpServletRequest request,NodeAgingForm entity) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "JDSXW");
		String agingUrl = "/raging/node_aging_list2";
		// 构建流程类型数据
		if (StringUtils.isNotBlank(entity.getCatagory())) {
			List<DicData> dicList = templateService.getProcessTypeByCatagory(entity.getCatagory()).getModel();
			ViewContext.put("processTypeList", dicList);
			List<String> processTypeList = new ArrayList<String>();
			if (StringUtils.isNotBlank(entity.getProcessType())) {
				processTypeList.add(entity.getProcessType());
			} else {
				for (DicData dic : dicList) {
					processTypeList.add(dic.getCode());
				}
			}
			entity.setProcessTypeList(processTypeList);
		}
		if (StringUtils.isNotBlank(entity.getOper()) && StringUtils.equalsIgnoreCase(entity.getOper(), "download")) {
			OutputStream os = null;
			try {
				entity.setPageIndex(0);
				entity.setPageSize(10000);
				List<Object[]> list = AgingService.listNodeAgingInfoUnfinished(entity).getData();
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=node-time-unfinished.xls");
				httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
				saveNodeAging(list, httpServletResponse.getOutputStream());
			} catch (Exception e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
			return null;
		} else {
			String billCode = entity.getBillCode() == null ? "" : entity.getBillCode();
			String catagory = entity.getCatagory() == null ? "" : entity.getCatagory();
			String processType = entity.getProcessType() == null ? "" : entity.getProcessType();
			String nodesNa = entity.getNodesNa() == null ? "" : entity.getNodesNa();
			String nodeAuditors = entity.getNodeAuditors() == null ? "" : entity.getNodeAuditors();
			String NodeTimeS = entity.getNodeTimeS() == null ? "" : entity.getNodeTimeS();
			String NodeTimeE = entity.getNodeTimeE() == null ? "" : entity.getNodeTimeE();
			String dateStart = entity.getDateStart() == null ? "" : entity.getDateStart();
			String dateEnd = entity.getDateEnd() == null ? "" : entity.getDateEnd();
			String nodeStatus = entity.getNodeStatus() == null ? "" : entity.getNodeStatus();
			String dateStartb = entity.getDateStartb() == null ? "" : entity.getDateStartb();
			String dateEndb = entity.getDateEndb() == null ? "" : entity.getDateEndb();

			agingUrl = UrlUtil.appendUrl(agingUrl, "billCode", billCode);
			agingUrl = UrlUtil.appendUrl(agingUrl, "catagory", catagory);
			agingUrl = UrlUtil.appendUrl(agingUrl, "processType", processType);
			agingUrl = UrlUtil.appendUrl(agingUrl, "nodesNa", nodesNa);
			agingUrl = UrlUtil.appendUrl(agingUrl, "nodeAuditors", nodeAuditors);
			agingUrl = UrlUtil.appendUrl(agingUrl, "NodeTimeS", NodeTimeS);
			agingUrl = UrlUtil.appendUrl(agingUrl, "NodeTimeE", NodeTimeE);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateStart", dateStart);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateEnd", dateEnd);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateStartb", dateStartb);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateEndb", dateEndb);
			agingUrl = UrlUtil.appendUrl(agingUrl, "nodeStatus", nodeStatus);
			agingUrl = agingUrl + "&pageIndex=";

			// 流程大类
			List<DicData> catagoryList = sysPermissionService.getDicDataByType("processCatagory");
			ViewContext.put("catagoryList", catagoryList);
			// 流程类型
			List<DicData> list = templateService.getProcessTypeByCatagory(entity.getCatagory()).getModel();
			ViewContext.put("processTypeList", list);
			List<ProcessInfoEntity> procedures = AgingService.getProcess();
			ViewContext.put("vo", entity);
			ViewContext.put("nodeAgingUrl", agingUrl);
			ViewContext.put("procedures", procedures);
			ViewContext.put("rowNum", AgingService.listNodeAgingInfoUnfinished(entity).getDbRowCount());
			return "aging/nodeAgingList2";
		}
	}
	

	/**
	 * 
	 * @Title: index
	 * @Description: 流程时效（已结束流程）
	 * @author user
	 * @param entity
	 * @return
	 * @return String
	 * @throws @date
	 *             2017年9月21日 下午2:26:33
	 */
	@RequestMapping("/process_aging")
	public String processAgingFinished(HttpServletResponse httpServletResponse, HttpServletRequest request,
			ProcessAgingForm entity) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "LCSXY");
		// 构建流程类型数据
		if (StringUtils.isNotBlank(entity.getCatagory())) {
			List<DicData> dicList = templateService.getProcessTypeByCatagory(entity.getCatagory()).getModel();
			ViewContext.put("processTypeList", dicList);
			List<String> processTypeList = new ArrayList<String>();
			if (StringUtils.isNotBlank(entity.getProcessType())) {
				processTypeList.add(entity.getProcessType());
			} else {
				for (DicData dic : dicList) {
					processTypeList.add(dic.getCode());
				}
			}
			entity.setProcessTypeList(processTypeList);
		}
		// 下载
		if (StringUtils.isNotBlank(entity.getOper()) && StringUtils.equalsIgnoreCase(entity.getOper(), "download")) {
			OutputStream os = null;
			try {
				entity.setPageIndex(0);
				entity.setPageSize(10000);
				List<Object[]> list = AgingService.listProcessAgingInfoFinished(entity).getData();
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=process-time-finished.xls");
				httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
				saveProcessAging(list, httpServletResponse.getOutputStream());
			} catch (Exception e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
			return null;
		} else {
			String agingUrl = "/raging/process_aging_list";
			String billCode = entity.getBillCode() == null ? "" : entity.getBillCode();
			String catagory = entity.getCatagory() == null ? "" : entity.getCatagory();
			String processType = entity.getProcessType() == null ? "" : entity.getProcessType();
			String processTimeS = entity.getProcessTimeS() == null ? "" : entity.getProcessTimeS();
			String processTimeE = entity.getProcessTimeE() == null ? "" : entity.getProcessTimeE();
			String dateStart = entity.getDateStart() == null ? "" : entity.getDateStart();
			String dateEnd = entity.getDateEnd() == null ? "" : entity.getDateEnd();
			String dateStartb = entity.getDateStartb() == null ? "" : entity.getDateStartb();
			String dateEndb = entity.getDateEndb() == null ? "" : entity.getDateEndb();
			String processStatus = entity.getProcessStatus() == null ? "" : entity.getProcessStatus();
			String province = entity.getProvince() == null ? "" : entity.getProvince();
			agingUrl = UrlUtil.appendUrl(agingUrl, "billCode", billCode);
			agingUrl = UrlUtil.appendUrl(agingUrl, "catagory", catagory);
			agingUrl = UrlUtil.appendUrl(agingUrl, "processType", processType);
			agingUrl = UrlUtil.appendUrl(agingUrl, "processTimeS", processTimeS);
			agingUrl = UrlUtil.appendUrl(agingUrl, "processTimeE", processTimeE);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateStart", dateStart);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateEnd", dateEnd);
			agingUrl = UrlUtil.appendUrl(agingUrl, "processStatus", processStatus);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateStartb", dateStartb);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateEndb", dateEndb);
			agingUrl = UrlUtil.appendUrl(agingUrl, "province", province);
			agingUrl = agingUrl + "&pageIndex=";
			// 流程大类
			List<DicData> catagoryList = sysPermissionService.getDicDataByType("processCatagory");
			ViewContext.put("catagoryList", catagoryList);
			// 流程类型
			List<DicData> list = templateService.getProcessTypeByCatagory(entity.getCatagory()).getModel();
			// 省区
			List<ActOrgEntity> provinceList = sysOrgService.getOrgProvince();
			ViewContext.put("provinceList", provinceList);
			ViewContext.put("processTypeList", list);
			ViewContext.put("vo", entity);
			ViewContext.put("processAgingUrl", agingUrl);
			ViewContext.put("rowNum", AgingService.listProcessAgingInfoFinished(entity).getDbRowCount());
			return "aging/processAgingList";
		}
	}

	public void saveProcessAging(List<Object[]> data, OutputStream outputStream) {
		// 模板
		String soucreFileName = "/excelTemplate/process-time-template.xls";
		DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(data);
		ExcelApiHelper.writeHandle(outputStream, AgingInfoListController.class.getResourceAsStream(soucreFileName),
				defaultRowWriteHandler);
	}
	
	
	public void saveNodeAging(List<Object[]> data, OutputStream outputStream) {
		// 节点模板
		String soucreFileName = "/excelTemplate/node_time_template.xls";
		DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(data);
		ExcelApiHelper.writeHandle(outputStream, AgingInfoListController.class.getResourceAsStream(soucreFileName),
				defaultRowWriteHandler);
	}

	/**
	 * 
	 * @Title: index
	 * @Description: 流程时效（未结束流程）
	 * @author user
	 * @param entity
	 * @return
	 * @return String
	 * @throws @date
	 *             2017年9月21日 下午2:26:33
	 */
	@RequestMapping("/process_aging2")
	public String processAgingUnfinished(HttpServletResponse httpServletResponse, HttpServletRequest request,
			ProcessAgingForm entity) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "LCSXW");
		// 构建流程类型数据
		if (StringUtils.isNotBlank(entity.getCatagory())) {
			List<DicData> dicList = templateService.getProcessTypeByCatagory(entity.getCatagory()).getModel();
			ViewContext.put("processTypeList", dicList);
			List<String> processTypeList = new ArrayList<String>();
			if (StringUtils.isNotBlank(entity.getProcessType())) {
				processTypeList.add(entity.getProcessType());
			} else {
				for (DicData dic : dicList) {
					processTypeList.add(dic.getCode());
				}
			}
			entity.setProcessTypeList(processTypeList);
		}
		// 下载
		if (StringUtils.isNotBlank(entity.getOper()) && StringUtils.equalsIgnoreCase(entity.getOper(), "download")) {
			OutputStream os = null;
			try {
				entity.setPageIndex(0);
				entity.setPageSize(10000);
				List<Object[]> list = AgingService.listProcessAgingInfoUnfinished(entity).getData();
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=process-time-unfinished.xls");
				httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
				saveProcessAging(list, httpServletResponse.getOutputStream());
			} catch (Exception e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
			return null;
		} else {
			String agingUrl = "/raging/process_aging_list2";
			String billCode = entity.getBillCode() == null ? "" : entity.getBillCode();
			String catagory = entity.getCatagory() == null ? "" : entity.getCatagory();
			String processType = entity.getProcessType() == null ? "" : entity.getProcessType();
			String processTimeS = entity.getProcessTimeS() == null ? "" : entity.getProcessTimeS();
			String processTimeE = entity.getProcessTimeE() == null ? "" : entity.getProcessTimeE();
			String dateStart = entity.getDateStart() == null ? "" : entity.getDateStart();
			String dateEnd = entity.getDateEnd() == null ? "" : entity.getDateEnd();
			String dateStartb = entity.getDateStartb() == null ? "" : entity.getDateStartb();
			String dateEndb = entity.getDateEndb() == null ? "" : entity.getDateEndb();
			String processStatus = entity.getProcessStatus() == null ? "" : entity.getProcessStatus();
			String province = entity.getProvince() == null ? "" : entity.getProvince();
			agingUrl = UrlUtil.appendUrl(agingUrl, "billCode", billCode);
			agingUrl = UrlUtil.appendUrl(agingUrl, "catagory", catagory);
			agingUrl = UrlUtil.appendUrl(agingUrl, "processType", processType);
			agingUrl = UrlUtil.appendUrl(agingUrl, "processTimeS", processTimeS);
			agingUrl = UrlUtil.appendUrl(agingUrl, "processTimeE", processTimeE);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateStart", dateStart);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateEnd", dateEnd);
			agingUrl = UrlUtil.appendUrl(agingUrl, "processStatus", processStatus);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateStartb", dateStartb);
			agingUrl = UrlUtil.appendUrl(agingUrl, "dateEndb", dateEndb);
			agingUrl = UrlUtil.appendUrl(agingUrl, "province", province);
			agingUrl = agingUrl + "&pageIndex=";
			// 流程大类
			List<DicData> catagoryList = sysPermissionService.getDicDataByType("processCatagory");
			ViewContext.put("catagoryList", catagoryList);
			// 流程类型
			List<DicData> list = templateService.getProcessTypeByCatagory(entity.getCatagory()).getModel();
			// 省区
			List<ActOrgEntity> provinceList = sysOrgService.getOrgProvince();
			ViewContext.put("provinceList", provinceList);
			ViewContext.put("processTypeList", list);
			ViewContext.put("vo", entity);
			ViewContext.put("processAgingUrl", agingUrl);
			ViewContext.put("rowNum", AgingService.listProcessAgingInfoUnfinished(entity).getDbRowCount());
			return "aging/processAgingList2";
		}
	}
}
